package edu.ccut.saturn.workflow.finishTaskModule.code;

import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnData;
import edu.ccut.saturn.workflow.model.ActivityInfo;
import edu.ccut.saturn.workflow.model.DataInfo;
import edu.ccut.saturn.workflow.model.WorkFlowInfo;

public class SetFormData extends DefaultComponent {
	@SuppressWarnings("unchecked")
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {
		HashMap<String,String> formdatavalue= (HashMap<String,String>) parameterContext.getParameterValue(0);//表单数据
		WorkFlowInfo workFlowInfo = (WorkFlowInfo) parameterContext.getParameterValue(1);//工作流定义
		SaturnData workItemData = (SaturnData) parameterContext.getParameterValue(2);//工作项
		HashMap<String,String> requestMap = (HashMap<String,String>)parameterContext.getParameterValue(3);
		// 获得当前工作项对应活动的定义id
		String activityId = workItemData.getString("activity_define_id");
		// 获得当前工作项对应活动的定义信息
		ActivityInfo activity = workFlowInfo.getActivityInfoById(activityId);
		List<DataInfo> dataInfos = activity.getFormData();
		for (int i = 0; i < dataInfos.size(); i++) {
			DataInfo dataInfo = dataInfos.get(i);
			String key = dataInfo.getKey();
			String value = (String) requestMap.get(key);
			if (value != null && !value.equals(""))// TODO 这里判断有待商榷
				formdatavalue.put(key, value);
		}
		StringBuffer sb = new StringBuffer();
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); 
		sb.append("<root>"); 
		sb.append("<data>");
		for (Entry formdata :formdatavalue.entrySet()) {
			String name = (String)formdata.getKey();
			String value = (String)formdata.getValue();
			sb.append("<" + name + ">"); 
			sb.append(value);
			sb.append("</" + name + ">"); 
		}
		sb.append("</data>"); 
		sb.append("</root>"); 
		parameterContext.setParameter(4, sb.toString().getBytes("UTF-8"));
		
		
	}
}